//
// Created by steven on 2017/2/23.
// Copyright (c) 2017 steven. All rights reserved.
//

#import "GMGuardListViewController.h"
#import "GMGuardTableViewCell.h"
#import "GMGuardCheckingTableViewCell.h"
#import "NSDate+Utils.h"
#import "GMComboListViewController.h"
#import "GMGuardDataController.h"
#import <MJRefresh/MJRefresh.h>

#define kGuardTableViewCellIdentifier @"kGuardTableViewCellIdentifier"

#define kUnusedTableViewCellIdentifier @"kUnusedTableViewCellIdentifier"
#define kUsedTableViewCellIdentifier @"kUsedTableViewCellIdentifier"
#define kCheckingTableViewCellIdentifier @"kCheckingTableViewCellIdentifier"

@interface GMGuardListViewController()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)GMGuardDataController *guardDataController;
@property (nonatomic, strong)NSMutableArray *unUsedGuards;
@property (nonatomic, strong)NSMutableArray *usedGuards;
@property (nonatomic, strong)NSMutableArray *checkingGuards;

@property (nonatomic, strong)UISegmentedControl *segmentedControl;
@property (nonatomic, strong)UIScrollView *scrollView;
@property (nonatomic, strong)UITableView *unusedTableView;
@property (nonatomic, strong)UITableView *usedTableView;
@property (nonatomic, strong)UITableView *checkingTableView;

@end

@implementation GMGuardListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.guardDataController = [[GMGuardDataController alloc] init];
    self.unUsedGuards = [[NSMutableArray alloc] init];
    self.usedGuards = [[NSMutableArray alloc] init];
    self.checkingGuards = [[NSMutableArray alloc] init];

    [self setupMainView];
    [self setMJRefresh];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    UIBarButtonItem *buyBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"购买守卫"
                                                                           style:UIBarButtonItemStylePlain
                                                                          target:self
                                                                          action:@selector(buyBarButtonItemPressed)];
    self.navigationItem.rightBarButtonItem = buyBarButtonItem;
    [self refreshUnusedGuards];
    [self refreshUsedGuards];
    [self refreshCheckingGuards];
}

#pragma mark - set up main view
- (void)setupMainView {
    self.navigationItem.title = @"守卫管理";
    
    // Add segmentedControl
    [self.view addSubview:self.segmentedControl];
    [self.segmentedControl addTarget:self action:@selector(didPressedSegmentedControl:) forControlEvents:UIControlEventValueChanged];
    
    // Add contentView
    [self.view addSubview:self.scrollView];
    
    [self.scrollView setContentSize:CGSizeMake(self.view.frame.size.width*3, self.view.frame.size.height-self.segmentedControl.frame.size.height)];
    
    [self.scrollView addSubview:self.unusedTableView];
    [self.scrollView addSubview:self.usedTableView];
    [self.scrollView addSubview:self.checkingTableView];
}

#pragma mark - set MJRefresh
- (void)setMJRefresh {

    __weak typeof(self) weakSelf = self;
    // unused tableview
    self.unusedTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if(weakSelf) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf refreshUnusedGuards];
        }
    }];

    self.unusedTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (weakSelf) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf loadMoreUnusedGuards];
        }
    }];
    self.unusedTableView.mj_footer.automaticallyHidden = YES;
    
    // used tableview
    self.usedTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if(weakSelf) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf refreshUnusedGuards];
        }
    }];
    
    self.usedTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (weakSelf) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf loadMoreUnusedGuards];
        }
    }];
    self.usedTableView.mj_footer.automaticallyHidden = YES;
    
    // checking tableview
    self.checkingTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if(weakSelf) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf refreshUnusedGuards];
        }
    }];
    
    self.checkingTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (weakSelf) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf loadMoreUnusedGuards];
        }
    }];
    self.checkingTableView.mj_footer.automaticallyHidden = YES;
}

/******************************** unused guards ***********************************/
#pragma mark - refresh unused
- (void)refreshUnusedGuards {
    NSDictionary *params = @{@"status":@"unused",@"page":@"1", @"perpage":PER_PAGE_RECORD};
    [self requestUnusedGuardsWithParams:params];
}

#pragma mark - load more unused
- (void)loadMoreUnusedGuards {
    NSInteger currentPage = self.guardDataController.unUsedGuardRecord.currentPage;
    NSInteger totalPage = self.guardDataController.unUsedGuardRecord.totalPage;
    if (currentPage < totalPage) {
        NSDictionary *params = @{@"status":@"unused",@"page":[NSString stringWithFormat:@"%ld", currentPage+1],@"perpage":PER_PAGE_RECORD};
        [self requestUnusedGuardsWithParams:params];
    } else {
        [self.unusedTableView.mj_footer endRefreshingWithNoMoreData];
    }
}

#pragma mark - request unused
- (void)requestUnusedGuardsWithParams:(NSDictionary *)params {
    [self.guardDataController getUnusedGuardsWithParams:params callback:^(NSString *error) {
        if (error == nil) {
            [self renderUnusedSuccessView];
        } else {
            [self showAlertMessage:error];
        }
    }];
}

/******************************** used guards ***********************************/
#pragma mark - refresh unused
- (void)refreshUsedGuards {
    NSDictionary *params = @{@"status":@"used",@"page":@"1", @"perpage":PER_PAGE_RECORD};
    [self requestUsedGuardsWithParams:params];
}

#pragma mark - load more unused
- (void)loadMoreUsedGuards {
    NSInteger currentPage = self.guardDataController.unUsedGuardRecord.currentPage;
    NSInteger totalPage = self.guardDataController.unUsedGuardRecord.totalPage;
    if (currentPage < totalPage) {
        NSDictionary *params = @{@"status":@"used",@"page":[NSString stringWithFormat:@"%ld", currentPage+1],@"perpage":PER_PAGE_RECORD};
        [self requestUsedGuardsWithParams:params];
    } else {
        [self.usedTableView.mj_footer endRefreshingWithNoMoreData];
    }
}

#pragma mark - request unused
- (void)requestUsedGuardsWithParams:(NSDictionary *)params {
    [self.guardDataController getUnusedGuardsWithParams:params callback:^(NSString *error) {
        if (error == nil) {
            [self renderUsedSuccessView];
        } else {
            [self showAlertMessage:error];
        }
    }];
}

/******************************** unused guards ***********************************/
#pragma mark - refresh unused
- (void)refreshCheckingGuards {
    NSDictionary *params = @{@"status":@"checking",@"page":@"1", @"perpage":PER_PAGE_RECORD};
    [self requestCheckingGuardsWithParams:params];
}

#pragma mark - load more unused
- (void)loadMoreCheckingGuards {
    NSInteger currentPage = self.guardDataController.unUsedGuardRecord.currentPage;
    NSInteger totalPage = self.guardDataController.unUsedGuardRecord.totalPage;
    if (currentPage < totalPage) {
        NSDictionary *params = @{@"status":@"checking",@"page":[NSString stringWithFormat:@"%ld", currentPage+1],@"perpage":PER_PAGE_RECORD};
        [self requestCheckingGuardsWithParams:params];
    } else {
        [self.checkingTableView.mj_footer endRefreshingWithNoMoreData];
    }
}

#pragma mark - request unused
- (void)requestCheckingGuardsWithParams:(NSDictionary *)params {
    [self.guardDataController getUnusedGuardsWithParams:params callback:^(NSString *error) {
        if (error == nil) {
            [self renderCheckingSuccessView];
        } else {
            [self showAlertMessage:error];
        }
    }];
}

#pragma mark - get combos success
- (void)renderUnusedSuccessView {
    [self.unusedTableView.mj_header endRefreshing];
    [self.unusedTableView.mj_footer endRefreshing];

    self.unUsedGuards = self.guardDataController.unUsedGuardRecord.guards;
    [self.unusedTableView reloadData];
}

#pragma mark - get combos success
- (void)renderUsedSuccessView {
    [self.usedTableView.mj_header endRefreshing];
    [self.usedTableView.mj_footer endRefreshing];
    
    self.usedGuards = self.guardDataController.usedGuardRecord.guards;
    [self.usedTableView reloadData];
}

#pragma mark - get combos success
- (void)renderCheckingSuccessView {
    [self.checkingTableView.mj_header endRefreshing];
    [self.checkingTableView.mj_footer endRefreshing];
    
    self.checkingGuards = self.guardDataController.checkingGuardRecord.guards;
    [self.checkingTableView reloadData];
}

#pragma mark - right barButton pressed
- (void)buyBarButtonItemPressed {
    GMComboListViewController *buyGuardViewController = [[GMComboListViewController alloc] init];
    [self.navigationController pushViewController:buyGuardViewController animated:YES];
}

#pragma mark - Getter for segmentedControl
- (UISegmentedControl *)segmentedControl {
    if (!_segmentedControl) {
        NSArray *titles = @[@"待使用",@"已使用",@"系统保护中"];
        _segmentedControl = [[UISegmentedControl alloc] initWithItems:titles];
        [_segmentedControl setFrame:CGRectMake(-3, 0, self.view.frame.size.width+6, 48)];
        [_segmentedControl setTintColor:BUTTON_ACTIVE_COLOR];
        [_segmentedControl setSelectedSegmentIndex:0];
        
    }
    
    return _segmentedControl;
}

#pragma mark - Getter for chargeTableView
- (UITableView *)unusedTableView {
    if (!_unusedTableView) {
        _unusedTableView = [[UITableView alloc] initWithFrame:self.scrollView.bounds];
        _unusedTableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
        _unusedTableView.delegate = self;
        _unusedTableView.dataSource = self;
        [_unusedTableView registerClass:[GMGuardTableViewCell class] forCellReuseIdentifier:kUnusedTableViewCellIdentifier];
    }
    
    return _unusedTableView;
}

#pragma mark - Getter for consumerTableView
- (UITableView *)usedTableView {
    if (!_usedTableView) {
        _usedTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.scrollView.frame.size.width, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height)];
        _usedTableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
        _usedTableView.delegate = self;
        _usedTableView.dataSource = self;
        [_usedTableView registerClass:[GMGuardTableViewCell class] forCellReuseIdentifier:kUsedTableViewCellIdentifier];
    }
    
    return _usedTableView;
}

#pragma mark - Getter for beanTableView
- (UITableView *)checkingTableView {
    if (!_checkingTableView) {
        _checkingTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.scrollView.frame.size.width*2, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height)];
        _checkingTableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
        _checkingTableView.delegate = self;
        _checkingTableView.dataSource = self;
        [_checkingTableView registerClass:[GMGuardCheckingTableViewCell class] forCellReuseIdentifier:kCheckingTableViewCellIdentifier];
    }
    
    return _checkingTableView;
}

#pragma mark - Getter for scrollView
- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.segmentedControl.frame.size.height, self.view.frame.size.width, self.view.frame.size.height-self.segmentedControl.frame.size.height)];
        [_scrollView setPagingEnabled:YES];
        [_scrollView setBounces:NO];
        _scrollView.delegate = self;
    }
    
    return _scrollView;
}

#pragma mark - SegmentedControl tapped event
- (void)didPressedSegmentedControl:(UISegmentedControl *)segmentedControl {
    NSInteger index = segmentedControl.selectedSegmentIndex;
    NSLog(@"%ld", index);
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width*index, 0)];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.unusedTableView) {
        return self.unUsedGuards.count;
    } else if(tableView == self.usedTableView) {
        return self.usedGuards.count;
    } else if(tableView == self.checkingTableView) {
        return self.checkingGuards.count;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GMGuardModel *guardModel = [[GMGuardModel alloc] init];
    
    if (tableView == self.unusedTableView) {
        guardModel = self.unUsedGuards[indexPath.row];
        GMGuardTableViewCell *cell = (GMGuardTableViewCell *)[tableView dequeueReusableCellWithIdentifier:kUnusedTableViewCellIdentifier forIndexPath:indexPath];
        cell.guardNoLabel.text = [NSString stringWithFormat: @"序列号 %@", guardModel.sn];
        cell.dateLabel.text = [NSString stringWithFormat:@"购买实践 %@", guardModel.useTime];
        
        return cell;
    } else if (tableView == self.usedTableView) {
        guardModel = self.usedGuards[indexPath.row];
        GMGuardTableViewCell *cell = (GMGuardTableViewCell *)[tableView dequeueReusableCellWithIdentifier:kUsedTableViewCellIdentifier forIndexPath:indexPath];
        cell.guardNoLabel.text = [NSString stringWithFormat: @"序列号 %@", guardModel.sn];
        cell.dateLabel.text = [NSString stringWithFormat:@"购买实践 %@", guardModel.useTime];
        cell.usageLabel.text = [NSString stringWithFormat:@"用户 %@", guardModel.usage];
        
        return cell;
    } else if (tableView == self.checkingTableView){
        guardModel = self.checkingGuards[indexPath.row];
        GMGuardCheckingTableViewCell *cell = (GMGuardCheckingTableViewCell *)[tableView dequeueReusableCellWithIdentifier:kCheckingTableViewCellIdentifier forIndexPath:indexPath];
        NSTimeInterval interval = [guardModel.checkingTime timeIntervalSinceNow];
        cell.hintLabel.text = [NSString stringWithFormat:@"由于异常退出，守卫暂时处于系统保护状态\n%@分钟后可继续使用", [self stringFromTimeInterval:interval]];
        return cell;
    } else {
        return nil;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 74;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (NSString *)stringFromTimeInterval:(NSTimeInterval)interval {
    NSInteger ti = (NSInteger)interval;
    NSInteger seconds = ti % 60;
    NSInteger minutes = (ti / 60) % 60;
//    NSInteger hours = (ti / 3600);
    return [NSString stringWithFormat:@"%02ld:%02ld", (long)minutes, (long)seconds];
}


@end
